/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int minDepth(TreeNode* root) {
        int maxn=0x3f3f3f3f;
        if(root==nullptr){return 0;}
        dfs(root,1,maxn);
        return maxn;
    }
    void dfs(TreeNode* root,int level,int& maxn){
        if(root->left==nullptr && root->right==nullptr){
            if(level<maxn){maxn=level;}
            return;
        }
        if(root->left!=nullptr){dfs(root->left,level+1,maxn);}
        if(root->right!=nullptr){dfs(root->right,level+1,maxn);}
        return;
    }
};